import axios from 'axios';

import { ElMessage } from 'element-plus'
//定义一个变量,记录公共的前缀  ,  baseURL
//const baseURL = 'http://localhost:8080';
import  {userTokenStore} from '@/stores/token.js' 
import router from '@/router';
const baseURL = '/api';
const instance = axios.create({ baseURL })
instance.interceptors.response.use(
    result=>{
        if(result.data.code===0){
            return result.data;
        }
        ElMessage.error(result.message?result.message:"服务异常")
        return Promise.reject(result.data)
    },
    err=>{
        if(err.response.status===401){
            ElMessage.error("请先登录")
            router.push('/login')
        }else{
            ElMessage.error("服务异常")
        }
        return Promise.reject(err)
    }
)
instance.interceptors.request.use(
    (config)=>{
        //请求前的回调
        //添加token
        const tokenStore = userTokenStore();
        //判断有没有token
        if(tokenStore.token){
            config.headers.Authorization = tokenStore.token
        }
        return config;
    },
    (err)=>{
        //请求错误的回调
        Promise.reject(err)
    }
)
export default instance;